﻿using UnityEngine;
using System.Collections;

public class Card : MonoBehaviour
{
    public static int chosenPlayerCardNum; // 被选中的玩家卡牌数量
    public static int chosenRepCardNum; // 被选中的候选卡牌数量
    public GameObject cardOwner;
    public bool chosen;
    public int code;

    public GameObject cardChosenAudio;
    private static GameManager gm;
    private float ratio = 1.1f;
    // Use this for initialization
    void Start()
    {
        chosenPlayerCardNum = 0;
        chosenRepCardNum = 0;
        gm = FindObjectOfType<GameManager>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void UnChosen()
    {
        OnMouseDown();
    }

    void OnMouseDown()
    {
        cardChosenAudio.GetComponent<AudioSource>().Play();
        // 更新UI和按钮计数
        if (!chosen)
        {
            transform.localScale *= ratio;
            if (cardOwner == gm.repCardTable)
                chosenRepCardNum++;
            else
                chosenPlayerCardNum++;
        }
        else
        {
            transform.localScale /= ratio;
            if (cardOwner == gm.repCardTable)
                chosenRepCardNum--;
            else
                chosenPlayerCardNum--;
        }
        chosen = !chosen;

        // 游戏逻辑更改
        switch (gm.status)
        {
            // 等待输入情况下选中牌
            // 游戏状态只会在WFA和S之间切换
            case GameManager.GameStatus.WaitForPlayer:
                if (chosenPlayerCardNum > 0)
                    gm.status = GameManager.GameStatus.PlayerSwap;
                break;
            // 抽牌并出牌情况下选中牌
            // 玩家只能点击确定按钮回到WFA状态
            // 需要更新当前玩家
            case GameManager.GameStatus.PlayerDealAndPut:
                // 只能出一张牌
                if (chosenPlayerCardNum != 1)
                    gm.DisableButton(gm.buttonOK);
                else
                    gm.EnableButton(gm.buttonOK);
                break;
            case GameManager.GameStatus.PlayerSwap:
                // 取消所有牌的选中后回到WFP状态
                if (chosenPlayerCardNum == 0 && chosenRepCardNum == 0)
                    gm.status = GameManager.GameStatus.WaitForPlayer;

                // 可换牌堆已满 可以换1张
                if (gm.IsRepFull())
                {
                    if (chosenPlayerCardNum == chosenRepCardNum && (chosenPlayerCardNum == 1 || chosenPlayerCardNum == 5))
                        gm.EnableButton(gm.buttonOK);
                    else
                        gm.DisableButton(gm.buttonOK);
                }
                // 未满 必须全换
                else
                {                    
                    if (chosenPlayerCardNum == gm.repCard.Count)
                        gm.EnableButton(gm.buttonOK);
                    else
                        gm.DisableButton(gm.buttonOK);
                }
                break;
        }


    }
}
